<?php
/* 
 *产品管理
 */
class ProductAction extends CommonAction {
    public function _filter(&$map) {
        $key = trim($_REQUEST['keywords']);
       /* if(strpos($key, ' ')){ //高级搜索，仅搜索产品名称

            $where = A('Search')->search($key);
            $map['_complex'] = $where;
       }else{//普通搜索 */
            if(!empty($key)) {
                $where['cas'] = array('like',"%".$key."%");
                $where['name'] = array('like',"%".$key."%");
                $where['formula'] = array('like',"%".$key."%");
                $where['ename'] = array('like',"%".$key."%");
                $where['_logic'] = "or";
                $map['_complex'] = $where;
            }

        if(!empty($_REQUEST['cat_id']))
            $map['cat_id'] = $_REQUEST['cat_id'];

       if(strpos(__ACTION__,'/search') !== false)
           $map['status'] = 1 ;//只展示正常的产品

    }

    public function _before_add(){
        $this->assign('cate_list',D('Category')->getAllCatalog(0,0));
        $this->assign('units',M('Unit')->where('status=1')->getField('id,name'));
        $this->assign('suppliers',M('Supplier')->where('status=1')->getField('id,name'));
    }

    public function _before_edit(){
        $this->assign('cate_list',D('Category')->getAllCatalog(0,0));
        $this->assign('units',M('Unit')->where('status=1')->getField('id,name'));
        $this->assign('suppliers',M('Supplier')->where('status=1')->getField('id,name'));
    }

    //相关询价记录
    public function asksup()
    {

        $map = 'product_id = '.intval($_REQUEST['id']) ;
        $count = M('Ask_supplier_detail')->where($map)->count();
        if($count > 0){
            import ( "@.ORG.Page" );
            $page = new Page($count,25);
            $ps = M('Ask_supplier_detail')->where($map)->limit($page->firstRow.','.$page->listRows)->order('update_time desc')->findAll(); 
            $assign_data = array(
                'products' => $ps,
                'page' => $page->show(),
            ); 
            $this->assign($assign_data);
        }
        $this->display();
    }

     //相关采购记录
    public function buy()
    {

        $map = 'product_id = '.intval($_REQUEST['id']) ;
        $count = M('Buy')->where($map)->count();
        if($count > 0){
            import ( "@.ORG.Page" );
            $page = new Page($count,25);
            $ps = M('Buy')->where($map)->limit($page->firstRow.','.$page->listRows)->order('update_time desc')->findAll(); 
            $assign_data = array(
                'products' => $ps,
                'page' => $page->show(),
            ); 
            $this->assign($assign_data);
        }
        $this->display();
    }

     //相关客户询盘记录
    public function inquiry()
    {

        $map = 'product_id = '.intval($_REQUEST['id']) ;
        $count = M('Inquiry')->where($map)->count();
        if($count > 0){
            import ( "@.ORG.Page" );
            $page = new Page($count,25);
            $ps = M('Inquiry')->where($map)->limit($page->firstRow.','.$page->listRows)->order('update_time desc')->findAll(); 
            $assign_data = array(
                'products' => $ps,
                'page' => $page->show(),
            ); 
            $this->assign($assign_data);
        }
        $this->display();
    }

      //相关销售记录
    public function order()
    {

        $map = 'product_id = '.intval($_REQUEST['id']) ;
        $count = D('OrderView')->where($map)->count();
        if($count > 0){
            import ( "@.ORG.Page" );
            $page = new Page($count,25);
            $ps = D('OrderView')->where($map)->limit($page->firstRow.','.$page->listRows)->order('update_time desc')->findAll(); 
            $assign_data = array(
                'products' => $ps,
                'page' => $page->show(),
            ); 
            $this->assign($assign_data);
        }
        $this->display();
    }

    public function micro_insert($data)
    {
        if(!empty($data))
             $_POST = $data;
        parent::micro_insert();
        unset($_POST);
    }

    public function insert()
    {   
        
        $jumpUrl = $_POST['jumpUrl'];
        $supplier_id = $_POST['supplier_id'];
         //B('FilterString');
        $name = 'Product';
        $model = D ($name);
        if(!empty($_POST['cas'])){
            $r = M('Product')->getByCas(trim($_POST['cas']));
            if($r)
                $this->error("CAS已经存在");
        }
        if(!empty($_POST['name'])){
            $r = M('Product')->getByName(trim($_POST['name']));
            if($r)
                $this->error("产品名已经存在");
        }
        if(!empty($_POST['ename'])){
            $r = M('Product')->getByEname(trim($_POST['ename']));
            if($r)
                $this->error("产品名已经存在");
        }
            
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
        //保存当前数据对象
        $list=$model->add ();
        if ($list!==false) { //保存成功
            if(!empty($supplier_id)){
                //insert into supplier_product table
                $map = array(
                    'supplier_id' => $supplier_id,
                    'product_id' => $list
                    );
                $rs = M('supplier_product')->where($map)->findAll();
                if(!is_array($rs))
                    M('supplier_product')->add($map);
            }
            

             $mod_field = getModelName ($list, $name,$field);
            //如果未取到字段值 ，则返回对应的ID编号
            $msg = '新增 '.$name.': '.$mod_field.' (编号：'.$list.')';
            if('Action' != $name)
                A('Action')->writeLog($msg,'新增',$name,$list);
            if(empty($jumpUrl))
                $jumpUrl = Cookie::get ( '_currentUrl_' );
            $this->assign ( 'jumpUrl',  $jumpUrl);
            $this->success ('新增成功!');
        } else {
            //失败提示
            $this->error ('新增失败!');
        }
    }

  

    /**
     * 产品批量修改页
     */
    public function massedit() {
        $id = $_REQUEST ['pid'];

        if (!isset($id)) {
            $this->error('请先选择产品！');
        }
        $model = M('Product');
        $condition = array('id' => array('in', explode(',', $id)));
        $list = $model->where($condition)->field('id,tm,name')->findAll();
        if (!is_array($list))
            $this->error('您选择的产品不存在！');

        $this->assign('list', $list);
        $this->_before_edit();
        $this->display();
    }

    /**
     * 批量修改处理
     */
    public function massUpdate(){
        if(empty ($_POST['product_id']))
            $this->error ("请选择要修改的产品");
        $data = $_POST;
        $changes = array();

        if(!empty ($data['regcode']))
            $changes['regcode'] = $data['regcode'];
        if(!empty ($data['helpword']))
            $changes['helpword'] = $data['helpword'];
        if(!empty ($data['cost_default']))
            $changes['cost_default'] = $data['cost_default'];
        if(!empty ($data['sale_price_default']))
            $changes['sale_price_default'] = $data['sale_price_default'];
        if(!empty ($data['wholesale_price_default']))
            $changes['wholesale_price_default'] = $data['wholesale_price_default'];
        if(!empty ($data['minstock']))
            $changes['minstock'] = $data['minstock'];
        if(!empty ($data['remark']))
            $changes['remark'] = $data['remark'];

        if( $data['unit_id'] != -1 )
           $changes['unit_id'] = $data['unit_id'];
        if( $data['cat_id'] != -1 )
           $changes['cat_id'] = $data['cat_id'];
        if( $data['supplier_id_default'] != -1 )
           $changes['supplier_id_default'] = $data['supplier_id_default'];
        if( $data['status'] != -1 )
           $changes['status'] = $data['status'];

        $map = array();
        $map['id'] = array('in',$_POST['product_id']);
        $old = M('Product')->where($map)->find();

        $records = M('Product')->where($map)->save($changes);
        if($records == 0)
            $this->error('批量修改失败！');

        //修改成功,记录日志
        $new = M('Product')->where($map)->find();
        $mod_field = getModelName($_POST['product_id']['0'], 'Product');
        $msg = '批量修改 Product: ' . $mod_field . ' (编号：' . implode(',',$_POST['product_id']) . ')';
        A('Action')->writeLog($msg, '批量修改', 'Product', implode(',',$_POST['product_id']), $old, $new);

        $this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
        $this->success('批量修改成功 '.$records.' 个产品！',false,2);
    }

    public function import_insert() {
        header("Content-Type:text/html; charset=utf-8");
        set_time_limit(0);
        
        import('@.ORG.PHPExcel.IOFactory','','.php');
        spl_autoload_register(array('Think','autoload'));   //必须重置，否则造成原TP类无法识别

        //处理上传文件
        if ($_FILES['upload']['name'] == '' || $_FILES['upload']['size'] <= 0)
            $this->error('请上传正确文件!');
        $ext = strtolower(substr($_FILES['upload']['name'], strrpos($_FILES['upload']['name'], '.') + 1));
        if ($ext != 'xls' && $ext != 'xlsx')
            $this->error('本功能仅支持excel');
        $filename = date('YmdHis') . '_product.xls';
        $status = move_uploaded_file($_FILES['upload']['tmp_name'], TEMP_PATH . $filename); //到temp目录
        if (!$status) {
            $this->error('上传失败，请重新上传');
            exit;
        }

        $inputFileName = TEMP_PATH . $filename;
        $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
        $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
        unlink(TEMP_PATH  . $filename); //上传后删除文件
        if (!$sheetData) {
            $this->error('上传数据失败或者上传的数据为空');
        }
        $supplier_id = $_REQUEST['supplier_id'];
        $this->__saveProduct($sheetData,$supplier_id);
    }

    protected  function __saveProduct($sheetData,$supplier_id = 0) {
       $product = M('Product');
       $supplier_product = M('Supplier_product');
        $data = array();
        $max_pid = $product->max('id');
        $i = 0; //产品计数

        //创建一个临时表，在500条数据以上时效率倍增，提高10-100倍以上
        $temp_sql = "create temporary table vm_tmp_product (id int(11) NOT NULL auto_increment PRIMARY KEY,`ename` varchar(200) NOT NULL COMMENT '货号',
  `cas` varchar(20) DEFAULT NULL COMMENT 'cas',
  `name` varchar(200) DEFAULT NULL COMMENT '产品名称',
  `formula` varchar(100) DEFAULT NULL COMMENT '产品名称',
  `weight` varchar(20) DEFAULT NULL COMMENT '进价',
  `nature` varchar(100) DEFAULT NULL COMMENT '产品性质',
  `status` tinyint(1) NOT NULL default '1',
  `nick_ename` varchar(200) DEFAULT NULL,
  `nick_name` varchar(200) DEFAULT NULL,
  `store_requirement` varchar(250) DEFAULT NULL,
  `create_time` int(11) NOT NULL default '0') ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 TYPE = HEAP;";
        M()->execute($temp_sql);
        $tmp_product = M('Tmp_product');

        foreach ($sheetData as $key => $value) {
            //$value = iconv("utf-8", "gb2312", var_export($value, true));    //转化为中文编码
            if ($key > 1) {//从第二行开始读取
                if(empty($value['A']) )
                   continue;
               $data = array(
                   'ename' => trim($value['A']),
                   'nick_ename' => trim($value['B']),
                   'name' => trim($value['C']),
                   'nick_name' => trim($value['D']),  
                   'cas' => trim($value['E']),   //单位名称，必须与系统中的名称一致
                   'formula' => $value['F'],
                   'weight' => $value['G'],
                   'nature' => $value['H'],
                   'store_requirement' => $value['I'],
                   'create_time' => time()
               );

               if( !empty($data['cas']) &&  $pid = M('Product')->where( 'cas = "' .$data['cas'] .'"' )->getField('id')  ){
                    if($supplier_id){ //add relation product-supplier
                        $dmpdata = array( 'supplier_id'=> $supplier_id,'product_id' => $pid ); 
                        $supplier_product->add( $dmpdata );
                        unset($dmpdata);
                    }
                    continue; //重复CAS直接使用原库中的
               }
               else if( empty($data['cas']) && !empty($data['ename'])  ){
                    if( $pid  = M('Product')->where( 'ename = "'. $data['ename'].'"' )->getField('id') ){
                        if($supplier_id){ //add relation product-supplier
                            $dmpdata =  array(
                                'supplier_id' => $supplier_id,
                                'product_id' => $pid,
                                );
                            $supplier_product->add( $dmpdata );
                            unset($dmpdata);
                        }
                        continue; //重复ename 直接使用原库中的
                    }

               }


                    $pid = $tmp_product->add($data);    //存入临时表
                if ($pid == 0) {
                    continue;
                }
            }
        }

        //TODO 重复数据处理 + 供应商产品关系管理

        //将临时表中的新数据插入到正式的产品表 增加ignore，如果表中存在相应记录，则忽略，继续其他数据插入
        $insert_sql = 'insert ignore  vm_product(ename,nick_ename,name,nick_name,cas,formula,weight,nature,store_requirement,create_time)
            select ename,nick_ename,name,nick_name,cas,formula,weight,nature,store_requirement,create_time from vm_tmp_product
            ';
        $i = M()->execute($insert_sql);
        //drop tmp table
        M()->execute('Drop table vm_tmp_product');

        if($i == 0)
            $this->error ("可能与系统中的产品重复，上传0个,请重新上传");
        
        //build relation with supplier and product
        if($supplier_id){
            $new_max_pid = $product->max('id');
            $supplier_product = M('Supplier_product');
            $sdata = array();
            for ($k=0 ; $k < $i ; $k++ ) { 
                $sdata = array(
                    'supplier_id' => $supplier_id,
                    'product_id' => ($new_max_pid - $k),
                    );
                $supplier_product -> add($sdata);
            }
        } 
            

        $message = '批量上传'.$i . '个产品';
        A('Action')->writeLog($message,'批量新增','Product',$max_pid);
        if(empty($supplier_id))
            $this->assign('jumpUrl', '__APP__/Product/index');
        else
            $this->assign('jumpUrl', '__APP__/Supplier/plist/id/'.$supplier_id);
        $this->success($message,false,2);
    }

}
?>
